package com.luych.toolbox.data.service.entity;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.luych.toolbox.common.enums.DataTransporterPlanStatus;
import com.luych.toolbox.common.service.base.BaseEntity;

import javax.persistence.*;
import java.util.HashMap;
import java.util.Map;

@Entity
@Table(name = "data_transporter_plan")
public class DataTransporterPlan extends BaseEntity {

    @Column(name = "data_source_from_id")
    private String dataSourceFromId;
    @Column(name = "data_source_to_id")
    private String dataSourceToId;
    @Column(name = "name")
    private String name;
    @Column(name = "tables")
    private String tables;
    @Column(name = "cron")
    private String cron;
    @Column(name = "status")
    @Enumerated(EnumType.STRING)
    private DataTransporterPlanStatus status;
    @Column(name = "owner_id")
    private String ownerId;

    public String getDataSourceFromId() {
        return dataSourceFromId;
    }

    public void setDataSourceFromId(String dataSourceFromId) {
        this.dataSourceFromId = dataSourceFromId;
    }

    public String getDataSourceToId() {
        return dataSourceToId;
    }

    public void setDataSourceToId(String dataSourceToId) {
        this.dataSourceToId = dataSourceToId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getTables() {
        return tables;
    }

    public Map<String, String> getTableMap() {
        if (tables == null) return new HashMap<>();
        try {
            return new ObjectMapper().readValue(tables, new TypeReference<Map<String, String>>() {});
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public void setTables(String tables) {
        this.tables = tables;
    }

    public void setTableMap(Map<String, String> tableMap) {
        if (tableMap == null) tables = null;
        try {
            tables = new ObjectMapper().writeValueAsString(tableMap);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public void putTableMap(String key, String value) {
        Map<String, String> tableMap = this.getTableMap();
        tableMap.put(key, value);
        this.setTableMap(tableMap);
    }

    public DataTransporterPlanStatus getStatus() {
        return status;
    }

    public void setStatus(DataTransporterPlanStatus status) {
        this.status = status;
    }

    public String getCron() {
        return cron;
    }

    public void setCron(String cron) {
        this.cron = cron;
    }

    public String getOwnerId() {
        return ownerId;
    }

    public void setOwnerId(String ownerId) {
        this.ownerId = ownerId;
    }
}